package com.example.base.rabbitmq;

import com.example.base.entity.*;
import com.example.base.service.DormitoryService;
import com.example.base.service.OrderService;
import com.example.base.utils.JsonUtil;
import com.example.base.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private DormitoryService dormitoryService;

    @Autowired
    private OrderService orderService;


    private void updateRelation(List<UserInfo> validUserList, Room room) {
        for (UserInfo info : validUserList) {
            UserDormRelation userDormRelation = new UserDormRelation();
            userDormRelation.setUid(info.getId());
            userDormRelation.setRoomId(room.getId());
            userDormRelation.setValid(true);
            dormitoryService.insertRelation(userDormRelation);
            dormitoryService.cacheRelation(info.getStudentNo(), userDormRelation);
        }
    }

    private void updateOrderInfo(List<UserInfo> validUserList, Integer orderId) {
        for (UserInfo info : validUserList) {
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUid(info.getId());
            orderInfo.setOrderId(orderId);
            orderService.insertOrderInfo(orderInfo);
        }
    }

    @RabbitListener(queues = "OrderQueue")
    public void receive(String msg) {
        log.info("接受消息：" + msg);
        OrderMessage orderMessage = JsonUtil.jsonStr2Object(msg, OrderMessage.class);
        if (orderMessage == null) return;
        Order order = orderMessage.getOrder();
        List<UserInfo> userList = orderMessage.getUserInfoList();
        Room room = orderMessage.getRoom();
        Room roomInfo = dormitoryService.getRoomById(room.getId());
        //最后一层判断，不能多选，不能性别不一致
        if (roomInfo.getRemain() < userList.size() ||
                !Objects.equals(userList.get(0).getGender(), roomInfo.getGender())) {
            return;
        }
        //更新房间剩余床位数量
        dormitoryService.updateRoomRemainById(room.getId(), room.getRemain() - userList.size());
        //更新用户宿舍关联表
        updateRelation(userList, room);
//        respBean = RespBean.success();
//        respBean.setMsg("获取的房间号为：" + getRoomInfo(room));
        orderService.insertOrder(order);
        // 更新订单详情表
        updateOrderInfo(userList, order.getId());
    }
}
